package com.second.app.thread.reentrant.condition;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author gyz
 * @date 2021/2/3 14:02
 */
public class MyService {

    /**
     * 实现多个线程顺序打印
     */

    private final ReentrantLock reentrantLock = new ReentrantLock();

    private final Condition conditionA = reentrantLock.newCondition();

    private final Condition conditionB = reentrantLock.newCondition();

    private final Condition conditionC = reentrantLock.newCondition();

    volatile Integer memoryValue = 1;

    public void waitA() {
        reentrantLock.lock();
        try {
            if (memoryValue != 1) {
                conditionA.await();
            }
            for (int i = 0; i < 3; i++) {
                System.out.println(Thread.currentThread().getName() + "打印：" + (i + 1));
            }
            memoryValue = 2;
            conditionB.signalAll();
        } catch (InterruptedException exception) {
            exception.printStackTrace();
        } finally {
            reentrantLock.unlock();
        }
    }

    public void waitB() {
        reentrantLock.lock();
        try {
            if (memoryValue != 2) {
                conditionB.await();
            }
            for (int i = 0; i < 3; i++) {
                System.out.println(Thread.currentThread().getName() + "打印：" + (i + 1));
            }
            memoryValue = 3;
            conditionC.signalAll();
        } catch (InterruptedException exception) {
            exception.printStackTrace();
        } finally {
            reentrantLock.unlock();
        }
    }

    public void waitC() {
        reentrantLock.lock();
        try {
            if (memoryValue != 3) {
                conditionA.await();
            }
            for (int i = 0; i < 3; i++) {
                System.out.println(Thread.currentThread().getName() + "打印：" + (i + 1));
            }
            memoryValue = 1;
            conditionA.signalAll();
        } catch (InterruptedException exception) {
            exception.printStackTrace();
        } finally {
            reentrantLock.unlock();
        }
    }
}
